package com.upf1sh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.upf1sh.bean.Snapshot;
import com.upf1sh.mapper.SnapshotMapper;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;

@Service

public class SnapshotService {
    @Resource
    private SnapshotMapper mapper;

    public int insert(Snapshot snapshot) {
        return mapper.insert(snapshot);
    }

    public int update1(Snapshot snapshot) {
        UpdateWrapper<Snapshot> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", 1).set("time", snapshot.getTime()).
                set("description", snapshot.getDescription()).
                set("size", snapshot.getSize()).
                set("name", snapshot.getName()).set("path", snapshot.getPath());
        return mapper.update(null, wrapper);
    }

    public Snapshot getSnapshot(int id) {
        return mapper.selectById(id);
    }


    public List<Snapshot> getAllSnapshot() {
        return mapper.selectList(null);
    }

    public Page<Snapshot> findAllSnapshotByPage(Page<Snapshot> page) {
//      调用basemapper的分页查询方法
        QueryWrapper<Snapshot> wrapper = new QueryWrapper<Snapshot>();
        return mapper.selectPage(page, wrapper);
    }

    public boolean saveSanpshot(MultipartFile file, String belong, String description) {
        val Snapshot = new Snapshot();
        LocalDateTime date2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString().replace("-", "") + originalFilename;
        String dirPath = ("/data");
//        String dirPath = System.getProperty("user.dir");
        String path = "/" + "Snapshot" + "/" + "snapshot.jpg";
        File destFile = new File(dirPath + path);
        Snapshot.setPath(dirPath + path);
        Snapshot.setBelong(belong);
        Snapshot.setName(originalFilename);
        Snapshot.setSize(file.getSize() / 1048576);
        Snapshot.setTime(date2);
        Snapshot.setDescription(description);

        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(destFile);
            update1(Snapshot);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
